<template>
  <div class="registration-management">
    <div class="header">
      <h2>挂号管理</h2>
      <el-button type="primary" @click="handleRefresh">
        <el-icon><Refresh /></el-icon>
        刷新数据
      </el-button>
    </div>

    <!-- 搜索栏 -->
    <div class="search-bar">
      <el-form :model="searchForm" inline>
        <el-form-item label="关键词">
          <el-input
            v-model="searchForm.keyword"
            placeholder="患者姓名、挂号编号、医生姓名"
            clearable
            @clear="handleSearch"
            style="width: 250px"
          />
        </el-form-item>
        <el-form-item label="挂号状态">
          <el-select v-model="searchForm.status"  filterable clearable placeholder="请选择状态" >
            <el-option label="全部" value="" />
            <el-option label="已预约" :value="0" />
            <el-option label="已就诊" :value="1" />
            <el-option label="已取消" :value="2" />
            <el-option label="已完成" :value="3" />
          </el-select>
        </el-form-item>
        <el-form-item label="挂号类型" >
          <el-select v-model="searchForm.type" placeholder="请选择类型" filterable clearable >
            <el-option label="全部" value="" />
            <el-option label="普通号" :value="1" />
            <el-option label="专家号" :value="2" />
            <el-option label="急诊号" :value="3" />
          </el-select>
        </el-form-item>
        <el-form-item label="预约日期">
          <el-date-picker
            v-model="searchForm.appointmentDate"
            type="date"
            placeholder="选择日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            clearable
          />
        </el-form-item>
        <el-form-item label="科室" >
          <el-tree-select
            v-model="searchForm.departmentId"
            :data="departmentList"
            node-key="id"
            :props="{
              label: 'name',
              value: 'id',
              children: 'children'
            }"
            placeholder="请选择科室"
            clearable
            filterable
            :render-after-expand="false"
            check-strictly
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="resetSearch">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 统计信息 -->
    <div class="statistics">
      <el-row :gutter="20">
        <el-col :span="6">
          <div class="stat-card">
            <div class="stat-number">{{ statistics.total }}</div>
            <div class="stat-label">总挂号数</div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="stat-card">
            <div class="stat-number">{{ statistics.pending }}</div>
            <div class="stat-label">待就诊</div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="stat-card">
            <div class="stat-number">{{ statistics.completed }}</div>
            <div class="stat-label">已完成</div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="stat-card">
            <div class="stat-number">{{ statistics.cancelled }}</div>
            <div class="stat-label">已取消</div>
          </div>
        </el-col>
      </el-row>
    </div>

    <!-- 挂号列表 -->
    <el-table
      :data="tableData"
      v-loading="loading"
      border
      stripe
      style="width: 100%"
      @sort-change="handleSortChange"
    >
      <el-table-column prop="registrationNo" label="挂号编号" width="140" />
      <el-table-column prop="userName" label="患者姓名" width="100" />
      <el-table-column prop="doctorName" label="医生姓名" width="100" />
      <el-table-column prop="departmentName" label="科室" width="120" />
      <el-table-column prop="appointmentDate" label="预约日期" width="110" sortable="custom">
        <template #default="{ row }">
          {{ formatDate(row.appointmentDate) }}
        </template>
      </el-table-column>
      <el-table-column prop="appointmentTime" label="预约时间" width="100">
        <template #default="{ row }">
          {{ formatTime(row.appointmentTime) }}
        </template>
      </el-table-column>
      <el-table-column prop="type" label="挂号类型" width="100">
        <template #default="{ row }">
          <el-tag :type="getTypeTagType(row.type)">
            {{ getTypeText(row.type) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="fee" label="挂号费" width="100">
        <template #default="{ row }">
          ¥{{ row.fee }}
        </template>
      </el-table-column>
      <el-table-column prop="queueNumber" label="队列号" width="80" />
      <el-table-column prop="status" label="状态" width="100">
        <template #default="{ row }">
          <el-tag :type="getStatusTagType(row.status)">
            {{ getStatusText(row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="挂号时间" width="160" sortable="custom">
        <template #default="{ row }">
          {{ formatDateTime(row.createTime) }}
        </template>
      </el-table-column>
      <el-table-column prop="remark" label="备注" min-width="150" show-overflow-tooltip />
      <el-table-column label="操作" width="300" fixed="right">
        <template #default="{ row }">
          <el-button type="primary" size="small" @click="handleViewDetail(row)">
            <el-icon><View /></el-icon>
            详情
          </el-button>
          <el-button
            v-if="row.status === 0"
            type="warning"
            size="small"
            @click="handleUpdateStatus(row, 1)"
          >
            确认就诊
          </el-button>
          <el-button
            v-if="row.status === 1"
            type="success"
            size="small"
            @click="handleUpdateStatus(row, 3)"
          >
            完成就诊
          </el-button>
          <!-- <el-button
            v-if="row.status === 0"
            type="danger"
            size="small"
            @click="handleUpdateStatus(row, 2)"
          >
            取消挂号
          </el-button> -->
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
        :current-page="pagination.page"
        :page-size="pagination.size"
        :page-sizes="[10, 20, 50, 100]"
        :total="pagination.total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="挂号详情"
      width="600px"
    >
      <div v-if="selectedRegistration" class="detail-content">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="挂号编号">
            {{ selectedRegistration.registrationNo }}
          </el-descriptions-item>
          <el-descriptions-item label="挂号状态">
            <el-tag :type="getStatusTagType(selectedRegistration.status)">
              {{ getStatusText(selectedRegistration.status) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="患者姓名">
            {{ selectedRegistration.userName }}
          </el-descriptions-item>
          <el-descriptions-item label="医生姓名">
            {{ selectedRegistration.doctorName }}
          </el-descriptions-item>
          <el-descriptions-item label="科室">
            {{ selectedRegistration.departmentName }}
          </el-descriptions-item>
          <el-descriptions-item label="挂号类型">
            <el-tag :type="getTypeTagType(selectedRegistration.type)">
              {{ getTypeText(selectedRegistration.type) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="预约日期">
            {{ formatDate(selectedRegistration.appointmentDate) }}
          </el-descriptions-item>
          <el-descriptions-item label="预约时间">
            {{ formatTime(selectedRegistration.appointmentTime) }}
          </el-descriptions-item>
          <el-descriptions-item label="挂号费">
            ¥{{ selectedRegistration.fee }}
          </el-descriptions-item>
          <el-descriptions-item label="队列号">
            {{ selectedRegistration.queueNumber }}
          </el-descriptions-item>
          <el-descriptions-item label="挂号时间">
            {{ formatDateTime(selectedRegistration.createTime) }}
          </el-descriptions-item>
          <el-descriptions-item label="更新时间">
            {{ formatDateTime(selectedRegistration.updateTime) }}
          </el-descriptions-item>
          <el-descriptions-item label="备注" :span="2">
            {{ selectedRegistration.remark || '无' }}
          </el-descriptions-item>
        </el-descriptions>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="detailDialogVisible = false">关闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Refresh, Search, View } from '@element-plus/icons-vue'
import request from '@/api/request'
import { getDepartmentTree, updateRegistrationStatus, getRegistrationDetail } from '@/api/business'

// 响应式数据
const loading = ref(false)
const tableData = ref([])
const departmentList = ref([])
const detailDialogVisible = ref(false)
const selectedRegistration = ref(null)

// 搜索表单
const searchForm = reactive({
  keyword: '',
  status: '',
  type: '',
  appointmentDate: '',
  departmentId: ''
})

// 分页数据
const pagination = reactive({
  page: 1,
  size: 20,
  total: 0
})

// 排序数据
const sortData = reactive({
  prop: '',
  order: ''
})

// 统计数据
const statistics = computed(() => {
  const total = tableData.value.length
  const pending = tableData.value.filter(item => item.status === 0).length
  const completed = tableData.value.filter(item => item.status === 3).length
  const cancelled = tableData.value.filter(item => item.status === 2).length
  
  return { total, pending, completed, cancelled }
})

// 页面加载时获取数据
onMounted(() => {
  fetchRegistrations()
  fetchDepartments()
})

// 获取挂号列表
const fetchRegistrations = async () => {
  loading.value = true
  try {
    const params = {
      page: pagination.page,
      size: pagination.size,
      ...searchForm
    }
    
    // 过滤空值
    Object.keys(params).forEach(key => {
      if (params[key] === '' || params[key] === null || params[key] === undefined) {
        delete params[key]
      }
    })

    const response = await request.get('/business/registrations', { params })
    
    if (response.code === 200) {
      // 如果返回的是数组，直接使用；如果是分页对象，取其中的数据
      if (Array.isArray(response.data)) {
        tableData.value = response.data
        pagination.total = response.data.length
      } else {
        tableData.value = response.data.list || []
        pagination.total = response.data.total || 0
      }
    } else {
      ElMessage.error(response.message || '获取挂号列表失败')
    }
  } catch (error) {
    console.error('获取挂号列表失败:', error)
    ElMessage.error('获取挂号列表失败')
  } finally {
    loading.value = false
  }
}

// 获取科室列表
const fetchDepartments = async () => {
  try {
    const response = await getDepartmentTree()
    if (response.code === 200) {
      departmentList.value = response.data
    }
  } catch (error) {
    console.error('获取科室列表失败:', error)
  }
}

// 搜索
const handleSearch = () => {
  pagination.page = 1
  fetchRegistrations()
}

// 重置搜索
const resetSearch = () => {
  Object.assign(searchForm, {
    keyword: '',
    status: '',
    type: '',
    appointmentDate: '',
    departmentId: ''
  })
  pagination.page = 1
  fetchRegistrations()
}

// 刷新数据
const handleRefresh = () => {
  fetchRegistrations()
}

// 分页大小改变
const handleSizeChange = (size) => {
  pagination.size = size
  pagination.page = 1
  fetchRegistrations()
}

// 当前页改变
const handleCurrentChange = (page) => {
  pagination.page = page
  fetchRegistrations()
}

// 排序改变
const handleSortChange = ({ prop, order }) => {
  sortData.prop = prop
  sortData.order = order
  fetchRegistrations()
}

// 查看详情
const handleViewDetail = async (row) => {
  try {
    loading.value = true
    const response = await getRegistrationDetail(row.id)
    if (response.code === 200) {
      selectedRegistration.value = response.data
      detailDialogVisible.value = true
    } else {
      ElMessage.error(response.message || '获取挂号详情失败')
    }
  } catch (error) {
    console.error('获取挂号详情失败:', error)
    ElMessage.error('获取挂号详情失败')
  } finally {
    loading.value = false
  }
}

// 更新挂号状态
const handleUpdateStatus = async (row, newStatus) => {
  const statusText = getStatusText(newStatus)
  const actionText = newStatus === 2 ? '取消' : '更新状态为'
  
  try {
    // 弹出确认对话框，并添加备注输入
    const { value: remark } = await ElMessageBox.prompt(
      `请输入${actionText}原因`,
      '确认操作',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        inputPlaceholder: '请输入备注信息',
        inputValidator: (value) => {
          if (!value) {
            return '备注不能为空'
          }
          return true
        }
      }
    )

    loading.value = true
    const response = await updateRegistrationStatus(row.id, newStatus, remark)

    if (response.code === 200) {
      ElMessage.success(`${actionText}成功`)
      // 刷新列表
      fetchRegistrations()
      // 如果详情对话框打开，也更新详情
      if (detailDialogVisible.value && selectedRegistration.value?.id === row.id) {
        const detailResponse = await getRegistrationDetail(row.id)
        if (detailResponse.code === 200) {
          selectedRegistration.value = detailResponse.data
        }
      }
    } else {
      ElMessage.error(response.message || `${actionText}失败`)
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error(`${actionText}失败:`, error)
      ElMessage.error(`${actionText}失败`)
    }
  } finally {
    loading.value = false
  }
}

// 获取状态文本
const getStatusText = (status) => {
  const statusMap = {
    0: '已预约',
    1: '已就诊',
    2: '已取消',
    3: '已完成'
  }
  return statusMap[status] || '未知'
}

// 获取状态标签类型
const getStatusTagType = (status) => {
  const typeMap = {
    0: 'warning',
    1: 'primary',
    2: 'danger',
    3: 'success'
  }
  return typeMap[status] || 'info'
}

// 获取类型文本
const getTypeText = (type) => {
  const typeMap = {
    1: '普通号',
    2: '专家号',
    3: '急诊号'
  }
  return typeMap[type] || '未知'
}

// 获取类型标签类型
const getTypeTagType = (type) => {
  const typeMap = {
    1: 'info',
    2: 'warning',
    3: 'danger'
  }
  return typeMap[type] || 'info'
}

// 格式化日期
const formatDate = (date) => {
  if (!date) return '-'
  return new Date(date).toLocaleDateString('zh-CN')
}

// 格式化时间
const formatTime = (time) => {
  if (!time) return '-'
  return time
}

// 格式化日期时间
const formatDateTime = (dateTime) => {
  if (!dateTime) return '-'
  return new Date(dateTime).toLocaleString('zh-CN')
}
</script>

<style scoped>
.registration-management {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header h2 {
  margin: 0;
  color: #303133;
}

.search-bar {
  background: #f5f7fa;
  padding: 20px;
  border-radius: 4px;
  margin-bottom: 20px;
}

.statistics {
  margin-bottom: 20px;
}

.stat-card {
  background: white;
  padding: 20px;
  border-radius: 4px;
  text-align: center;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.stat-number {
  font-size: 32px;
  font-weight: bold;
  color: #409eff;
  margin-bottom: 8px;
}

.stat-label {
  font-size: 14px;
  color: #909399;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.detail-content {
  padding: 20px 0;
}

.dialog-footer {
  text-align: right;
}

:deep(.el-table) {
  font-size: 14px;
}

:deep(.el-table th) {
  background-color: #f5f7fa;
  color: #606266;
  font-weight: 600;
}

:deep(.el-form-item__label) {
  font-weight: 600;
}

:deep(.el-dialog__header) {
  background-color: #f5f7fa;
  padding: 20px 20px 10px;
}

:deep(.el-dialog__title) {
  font-weight: 600;
  color: #303133;
}

:deep(.el-descriptions__label) {
  font-weight: 600;
}
</style>
